//
//  ViewController.m
//  AesDemo
//
//  Created by kingboyrang on 2019/5/11.
//  Copyright © 2019 wulanzhou. All rights reserved.
//

#import "ViewController.h"
#import "AESBaseCryptor.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //加解密key
    NSString *appkey = @"UxCn6hNCtvYOB%ED";
    
    //要加密的字典
    NSDictionary *body = @{
                           @"v":@"1.0.0",
                           @"agentCode":@"zte001",
                           @"pv":@"iphone",
                           @"uid":@"1"};
    
    //1.加密
    NSData *rsBody = [AESBaseCryptor encryptWithKey:appkey data:body];
    NSString *encryStr= [[NSString alloc] initWithData:rsBody encoding:NSUTF8StringEncoding];
    
    NSLog(@"加密后的字符串:%@",encryStr);
    
    //2.解密
    NSString *decstring=[AESBaseCryptor decryptWithKey:appkey data:rsBody];
    NSLog(@"解密结果:%@", decstring);
    
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)postWith:(NSString *)urlStr params:(NSDictionary *)params{
    
    NSDictionary *header = @{
                             @"Content-type":@"application/json;charset=utf-8"
                             };
    
    //数据加密请求
    NSString *appkey = @"UxCn6hNCtvYOB%ED";
    NSData *rsBody = [AESBaseCryptor encryptWithKey:appkey data:params];
    
    
    NSMutableURLRequest *req=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
    //头部设置
    [req setAllHTTPHeaderFields:header];
    //超时设置
    [req setTimeoutInterval:60.0f];
    //访问方式
    [req setHTTPMethod:@"POST"];
    
    [req setHTTPBody:rsBody];
    
    
    // 3.向服务器发送异步请求
    [NSURLConnection sendAsynchronousRequest:req queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        // 请求完毕会来到这个block
        
        // 4.解析服务器返回的数据（解析成字符串）
        //NSLog(@"data = %@",[data class]);
        // NSLog(@"connectionError =%@", connectionError);
        if (data) {
            NSString *stringStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"加密请求结果 =%@", stringStr);
            NSString *string=[AESBaseCryptor decryptWithKey:appkey data:data];
            
            NSLog(@"解密结果:%@", string);
            
        }else{
            NSLog(@"请求失败!");
        }
        
        
    }];
    
}

@end
